//引入 路由 和 request 模块
import { Router } from 'express';
import request from 'request'

const router = Router();

//授权请求接口
router.get('http://test.keoconf.com/mobile' , function (req , res , next) {
    //用户同意授权，获取code
    let router = 'get_access_token';
    let AppID = 'wxecef89a140ce2a41';
    //编码后的地址
    let return_url = 'http%3A%2F%2Fm.keoconf.com%2Fapi%2F' + router ;
    let scope = 'snsapi_userinfo';

    //重定向到微信授权链接
    res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + AppID + '&redirect_uri=' + return_url + '&response_type=code&scope=' + scope + '&state=STATE#wechat_redirect');
})

router.get('/get_access_token',function (req, res, next) {

    //第二步：通过code获取网页的access_token
    let code = req.query.code;

    request.get({
            url:'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + AppID + '&secret='+ AppSecret + '&code=' + code + '&grant_type=authorization_code'
        },
        function (error, response, body) {
            if( response.statusCode == 200 ){

                // 第三步：拉取用户信息(需scope为 snsapi_userinfo)

                let data = JSON.parse( body );
                let access_token = data.access_token;
                let openid = data.openid;

                request.get({
                        url : 'https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN',
                    },
                    function (error, response, body) {
                        if( response.statusCode == 200 ){
                            // 第四步：根据获取的用户信息进行对应操作
                            let userinfo = JSON.parse(body);

                            console.log(userinfo);

                            res.send("\
                                <h1>openid:" + userinfo.openid +  "</h1>\
                                <h1>"+userinfo.nickname+" 的个人信息</h1>\
                                <p>![]("+userinfo.headimgurl+")</p>\
                                <p>"+userinfo.city+"，"+userinfo.province+"，"+userinfo.country+"</p>\
                                ")
                        }else{
                            console.log(response.statusCode);
                        }
                    }
                )
            }else{
                console.log(response.statusCode);
            }
        }
    )
})

export default router
